<template>
  <div class="shop-manage">
    <div class="fl">
      <ShopListMenu @emitShopId="emitShopId" />
    </div>
    <div
      v-if="shopId"
      v-loading="loading"
      class="left-container app-main-content-box"
    >
      <app-main-title :title="shopName ? shopName : ''" />

      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-width="140px"
        label-suffix="："
        size="small"
      >
        <el-form-item prop="orderTypes" label="用餐方式">
          <el-checkbox-group
            v-model="form.orderTypes"
            @change="changeOrdertype"
          >
            <el-checkbox
              v-for="(item, index) in orderTypesOptions"
              :key="index"
              :label="item.label"
              >{{ item.value }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!--        堂食-->
        <div
          v-show="form.orderTypes.findIndex((item) => item == 1) != -1"
          class="order_type"
        >
          <el-form-item prop="hallFoodMode" label="堂食结算模式">
            <el-radio-group v-model="form.hallFoodMode">
              <div>
                <el-radio :label="1"
                  >先付款后用餐<span class="falg"
                    >(顾客点餐，付款完成后，后厨出票上单，加菜需要再下新单)</span
                  ></el-radio
                >
              </div>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="hallFoodDinersStatus" label="就餐人数开关">
            <el-radio-group v-model="form.hallFoodDinersStatus">
              <div>
                <el-radio :label="1">开</el-radio>
                <el-radio :label="0">关</el-radio>
              </div>
            </el-radio-group>
            <div class="falg">
              (开启就餐人数后用户下单前必选人数，关闭后用户无需选择人数，堂食茶位费无法收取)
            </div>
          </el-form-item>
          <el-form-item
            prop="teaFee"
            :rules="rules.dinePrice"
            label="堂食茶位费"
          >
            <div class="inline_input">
              每人收取<el-input
                v-model="form.teaFee"
                placeholder="请输入内容"
                class="input"
                ><template slot="append">元</template></el-input
              >
            </div>
            <div class="falg">
              （顾客堂食消费时，订单、小票将自动添加茶位费）
            </div>
          </el-form-item>
        </div>

        <!--        打包-->
        <div
          v-show="form.orderTypes.findIndex((item) => item == 2) != -1"
          class="order_type"
        >
          <el-form-item label="打包结算模式">
            <el-radio-group v-model="form.packMode">
              <div>
                <el-radio :label="1"
                  >先付款后用餐
                  <span class="falg"
                    >(顾客点餐，付款完成后，后厨出票上单，加菜需要再下新单)</span
                  >
                </el-radio>
              </div>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="packDinersStatus" label="就餐人数开关">
            <el-radio-group v-model="form.packDinersStatus">
              <div>
                <el-radio :label="1">开</el-radio>
                <el-radio :label="0">关</el-radio>
              </div>
            </el-radio-group>
            <div class="falg">
              (开启就餐人数后用户下单前必选人数，关闭后用户无需选择人数)
            </div>
          </el-form-item>
          <el-form-item
            prop="packFee"
            :rules="rules.dinePrice"
            label="打包费用"
          >
            <div class="inline_input">
              每单收取<el-input
                v-model="form.packFee"
                placeholder="请输入内容"
                class="input"
              >
                <template slot="append">元</template>
              </el-input>
            </div>
            <div class="falg">
              （顾客堂食消费时，订单、小票将自动添加打包费）
            </div>
          </el-form-item>
        </div>

        <!--        外卖配送-->
        <div
          v-show="form.orderTypes.findIndex((item) => item == 3) != -1"
          class="order_type"
        >
          <el-form-item label="外卖配送结算模式" />
          <el-form-item prop="deliveryDinersStatus" label="就餐人数开关">
            <el-radio-group v-model="form.deliveryDinersStatus">
              <div>
                <el-radio :label="1">开</el-radio>
                <el-radio :label="0">关</el-radio>
              </div>
            </el-radio-group>
            <div class="falg">
              (开启就餐人数后用户下单前必选人数，关闭后用户无需选择人数)
            </div>
          </el-form-item>
          <el-form-item
            prop="startingPriceDelivery"
            :rules="rules.dinePrice"
            label="起送价"
          >
            <div class="inline_input">
              <el-input
                v-model="form.startingPriceDelivery"
                placeholder="请输入内容"
                class="input"
              >
                <template slot="append">元</template>
              </el-input>
            </div>
            <div class="falg">
              （填写后，优惠前商品合计金额少于起送价，将会无法下单）
            </div>
          </el-form-item>
          <el-form-item
            prop="packFeeDelivery"
            :rules="rules.dinePrice"
            label="打包费"
          >
            <div class="inline_input">
              每单收取<el-input
                v-model="form.packFeeDelivery"
                placeholder="请输入内容"
                class="input"
              >
                <template slot="append">元</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item
            prop="feeDelivery"
            :rules="rules.dinePrice"
            label="配送费"
          >
            <div class="inline_input">
              <el-input
                v-model="form.feeDelivery"
                placeholder="请输入内容"
                class="input"
              >
                <template slot="append">元</template>
              </el-input>
            </div>
            <div class="falg">（填写后，顾客下单时需额外支付配送费）</div>
          </el-form-item>
          <el-form-item
            prop="distanceDelivery"
            :rules="rules.dineDince"
            label="配送距离"
          >
            <div class="inline_input">
              <el-input
                v-model="form.distanceDelivery"
                placeholder="请输入内容"
                class="input"
              >
                <template slot="append">KM</template>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item prop="stockUp" label="备货时间">
            <div class="inline_input">
              <el-select v-model="form.stockUp" placeholder="请选择">
                <el-option
                  v-for="(item, index) in 49"
                  :key="index * 0.5"
                  :label="index * 0.5"
                  :value="index * 0.5"
                />
              </el-select>
              <div class="el-input-group__append append">小时</div>
            </div>
            <div class="falg">
              （填写后，顾客选择预约送达时间至少在备货时间之后）
            </div>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button size="small" round type="primary" @click="submit"
            >保存</el-button
          >
          <el-button size="small" round @click="fetchData">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getShopManageConfig,
  saveShopManageConfig,
} from "@/views/wcyModule/api/shop";
import {
  validateCustomPositiveInt,
  validateCustomTwoDecimal,
} from "@/utils/validate";

export default {
  data() {
    const validatorPrice = (rule, value, callback) => {
      const customStr = "";
      const reg = /^\d{1,6}(\.\d{1,2})?$/;
      if (!value) {
        callback(new Error("请输入费用"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入0，正整数，正小数（小数位不超过2位）"));
      } else {
        callback();
      }
    };
    const validatorDince = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入配送距离"));
      } else if (
        value < 1 ||
        value >= 100000 ||
        String(value).indexOf(".") > -1
      ) {
        callback(new Error("请输入1-99999之间的整数"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        orderTypes: [
          {
            type: "array",
            required: true,
            message: "请至少选择一种用餐方式",
            trigger: "change",
          },
        ],
        delayTakeTime: [
          {
            required: true,
            message: "请选择可提前下单时间",
            trigger: "change",
          },
        ],
        isUseTableNo: [
          { required: true, message: "请选择点餐模式", trigger: "change" },
        ],
        isOpen: [{ required: true, message: "是否营业", trigger: "change" }],
        dinePrice: [
          {
            required: true,
            validator: validatorPrice,
            trigger: ["blur", "change"],
          },
        ],
        dineDince: [
          {
            required: true,
            validator: validatorDince,
            trigger: ["blur", "change"],
          },
        ],
      },
      // 配置
      // 用餐方式
      orderTypesOptions: [
        {
          label: 1,
          value: "堂食",
        },
        {
          label: 2,
          value: "打包",
        },
        {
          label: 3,
          value: "外卖配送",
        },
      ],
      // 支付方式
      payTypesOptions: [
        {
          label: 1,
          value: "微信支付",
        },
        {
          label: 3,
          value: "会员钱包",
        },
      ],
      // 时间
      delayTakeTimeOptions: [
        {
          value: 30,
          label: "30分钟",
        },
        {
          value: 60,
          label: "60分钟",
        },
        {
          value: 90,
          label: "90分钟",
        },
        {
          value: 120,
          label: "120分钟",
        },
      ],
      // 状态
      loading: false,
      // 数据
      shopId: "",
      shopName: "",
      form: {
        customParamsOpenTime: "",
        isOpen: true,
        isUseTableNo: true,
        delayTakeTime: "",
        orderTypes: [1],
        payTypes: [1],
        // 打包费用
        packFee: 0,
        packMode: 1,
        // 堂食费用
        teaFee: 0,
        hallFoodMode: 1,
        hallFoodDinersStatus: 1,
        packDinersStatus: 1,
        deliveryDinersStatus: 1,
        shopNotice: "",
        openTimeType: 1,
        startingPriceDelivery: 0,
        packFeeDelivery: 0,
        feeDelivery: 0,
        distanceDelivery: 0,
        stockUp: 0,
      },
    };
  },
  methods: {
    /**
     * 获取数据
     */
    // 获取配置
    fetchData() {
      this.loading = true;
      getShopManageConfig({ shopId: this.shopId })
        .then((res) => {
          // 格式化时间
          const data = res.data;
          const { openHour, openMin, closeHour, closeMin } = data;
          data.customParamsOpenTime = [
            `${openHour}:${openMin}`,
            `${closeHour}:${closeMin}`,
          ];
          data.payTypes = data.payTypes || [1];
          data.orderTypes = data.orderTypes || [1];
          data.delayTakeTime = data.delayTakeTime || "";
          data.packFee = data.packFee || "0";
          data.teaFee = data.teaFee || "0";
          data.openTimeType = data.openTimeType;
          data.packMode = data.packMode || 1;
          data.hallFoodMode = data.hallFoodMode || 1;
          data.packDinersStatus =
            data.packDinersStatus !== null && data.packFeeDelivery !== undefined
              ? data.packDinersStatus
              : 1;
          data.hallFoodDinersStatus =
            data.hallFoodDinersStatus !== null &&
            data.hallFoodDinersStatus !== undefined
              ? data.hallFoodDinersStatus
              : 1;
          data.deliveryDinersStatus =
            data.deliveryDinersStatus !== null &&
            data.deliveryDinersStatus !== undefined
              ? data.deliveryDinersStatus
              : 1;
          data.openTimeType = data.openTimeType || 1;
          data.distanceDelivery = data.distanceDelivery || 1;
          data.startingPriceDelivery = data.startingPriceDelivery || "0";
          data.feeDelivery = data.feeDelivery || "0";
          data.packFeeDelivery = data.packFeeDelivery || "0";
          data.stockUp = data.stockUp || "0";
          this.form = data;
          console.log(this.form);
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          });
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 按钮组
     */
    // 保存
    submit() {
      this.$refs.form.validate((valid) => {
        console.log(this.form);

        if (valid) {
          console.log(this.form);
          // 格式化时间
          const params = Object.assign({}, this.form);
          const openTime = params.customParamsOpenTime[0].split(":");
          const closeTime = params.customParamsOpenTime[1].split(":");
          params.openHour = openTime[0];
          params.openMin = openTime[1];
          params.closeHour = closeTime[0];
          params.closeMin = closeTime[1];
          params.shopId = this.shopId;
          delete params.customParamsOpenTime;
          this.loading = true;
          saveShopManageConfig(params)
            .then((res) => {
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
                duration: 2000,
                offset: 40,
              });
              this.loading = false;
            })
            .catch((err) => {})
            .finally(() => {});
        }
      });
    },

    // 选中门店
    emitShopId(item) {
      this.shopId = item.shopId;
      this.shopName = item.shopName;
      this.fetchData();
    },
    changeOrdertype(e) {
      console.log(e);
    },
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 左边 */
.left-container {
  overflow: hidden;
}
.order_type {
  .falg {
    color: #bebebe;
  }
  .inline_input {
    display: flex;
    .input {
      max-width: 200px;
      margin-left: 10px;
    }
  }
}
.open_type {
  line-height: 32px !important;
  display: flex;
  height: 32px;
  align-items: center;
  > div {
    display: flex;
    align-content: center;
    div {
      display: inline-block;
      width: 30px;
      height: 30px;
    }
  }
}
.append {
  display: flex !important;
  width: auto !important;
}
</style>
